package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;

public class BibliotecaApp {

    private PrintStream printStream;
    private LibraryManager manager;

    public BibliotecaApp(PrintStream printStream, LibraryManager manager) {
        this.printStream = printStream;
        this.manager = manager;
    }

    public void runApp() {
        welcomeMessage();
        manager.listAvailableBooks();
        displayListOptions();
        handleUserListChoice(new BufferedReader(new InputStreamReader(System.in)), new UserInputCondition());
    }


    public void welcomeMessage() {
        printStream.println("Welcome to Biblioteca!");
        printStream.println();
    }

    public void displayListOptions() {
        printStream.println("Enter Number for Option.");
        printStream.println("Enter 1 to list books");
        printStream.println("Enter 2 to checkout book");
        printStream.println("Enter 3 to return book");
    }


    public void handleUserListChoice(BufferedReader reader, UserInputCondition condition) {
        String input;

        while (condition.isTrue()) {
            try {
                input = getUserInput(reader);
                processUserInput(input, reader);
            } catch (IOException e) {
                printStream.println("Error reading from user.");
            }
        }
    }

    private String getUserInput(BufferedReader reader) throws IOException {
        String input = "0";

        input = reader.readLine();
        return input;
    }

    private void processUserInput(String input, BufferedReader reader) throws IOException {

        if(input.equals("1")){
            manager.listAvailableBooks();
        } else if (input.equals("2")) {
            manager.checkOutBook();
        } else if (input.equals("3")) {
            manager.returnItem();
        } else{
            printStream.println("Select a valid option!");
        }
    }


}